package com.ymh.service.impl;

import com.ymh.common.enums.StatusCodeEnum;
import com.ymh.common.exception.CustomException;
import com.ymh.dao.AccountDao;
import com.ymh.domain.AccountDTO;
import com.ymh.domain.AccountDO;

import com.ymh.service.AccountService;
import java.math.BigDecimal;
import java.util.Optional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: 13590
 * @date: 2020/10/27 18:25
 * @description:
 */
@Service
public class AccountServiceImpl implements AccountService {

  @Autowired
  private AccountDao accountDao;

  @Override
  public AccountDTO selectByCode(String accountCode) {

    Optional<AccountDO> optional = accountDao
        .findOne(Example.of(new AccountDO().setAccountCode(accountCode)));
    AccountDTO accountDTO = new AccountDTO();
    optional.ifPresent(accountDO -> BeanUtils.copyProperties(accountDO, accountDTO));
    return accountDTO;
  }

  @Override
  @Transactional(rollbackFor = CustomException.class)
  public AccountDTO updateAccount(AccountDTO accountDTO) {
    AccountDO accountDO = new AccountDO();
    BeanUtils.copyProperties(accountDTO, accountDO);
    accountDao.save(accountDO);
    return accountDTO;
  }

  @Override
  @Transactional(rollbackFor = CustomException.class)
  public AccountDTO insertAccount(AccountDTO accountDTO) {
    AccountDO accountDO = new AccountDO();
    BeanUtils.copyProperties(accountDTO, accountDO);
    accountDao.save(accountDO);
    return accountDTO;
  }

  @Override
  @Transactional(rollbackFor = CustomException.class)
  public void deleteAccount(String accountCode) {
    accountDao.delete(new AccountDO().setAccountCode(accountCode));
  }

  @Override
  @Transactional(rollbackFor = CustomException.class)
  public void reduce(String accountCode, BigDecimal amount) {
    Optional<AccountDO> optional = accountDao
        .findOne(Example.of(new AccountDO().setAccountCode(accountCode)));
    AccountDO accountDO = optional
        .orElseThrow(() -> new CustomException(StatusCodeEnum.COMMON_EX_STATUS_CODE.getStatus(),
            "can't reduce amount,account is null"));

    BigDecimal subAmount = accountDO.getAmount().subtract(amount);
    if (subAmount.compareTo(BigDecimal.ZERO) < 0) {
      throw new CustomException(StatusCodeEnum.COMMON_EX_STATUS_CODE.getStatus(),
          "can't reduce amount,account'amount is less than reduce amount");
    }
    accountDO.setAmount(subAmount);
    accountDao.save(accountDO);
  }


}
